/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.starlink.common.strategy.paynotify;

import com.starlink.common.enums.OrderRefundEnum;
import com.starlink.common.enums.OrderStatusEnum;
import com.starlink.common.enums.OrderTypeEnum;
import com.starlink.common.strategy.IPayNotify;
import com.starlink.context.SessionContext;
import com.starlink.mapper.MallBooksOrderDetailsMapper;
import com.starlink.mapper.MallBooksOrderMapper;
import com.starlink.mapper.MallRefundsMapper;
import com.starlink.model.domain.MallBooksOrderDO;
import com.starlink.model.domain.MallPaymentDO;
import com.starlink.model.domain.MallRefundsDO;
import com.starlink.model.request.MallPaymentRequest;
import com.starlink.model.request.MallRefundPriceRequest;
import com.starlink.model.request.mall.WechatPay;
import com.starlink.model.request.mall.WechatRefund;
import com.starlink.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.starlink.common.enums.OperationTypeEnum.ADMIN_REFUND_PRICE;
import static com.starlink.common.enums.OrderStatusEnum.*;

/**
 * @author zhanghong
 * @version BookPayNotify.java, v 0.1 2024/4/11 23:02 下午 BookPayNotify Exp $$
 */
@Component
public class BookPayNotify implements IPayNotify {

    @Autowired
    private MallBooksOrderMapper orderMapper;
    @Autowired
    private MallOrderService orderService;
    @Autowired
    private MallBooksOrderDetailsMapper mallBooksOrderDetailsMapper;
    @Autowired
    private MallOrderDetailsService orderDetailsService;
    @Autowired
    private MallPaymentService paymentService;
    @Autowired
    private MallBooksSpecificationService specificationService;
    @Autowired
    private MallRefundPriceService refundPriceService;
    @Autowired
    private MallRefundsMapper refundsMapper;

    @Override
    public boolean supports(Integer orderType) {
        return orderType.equals(OrderTypeEnum.BOOK.getType());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handle(WechatPay wechatPay) {
        Long orderId = Long.valueOf(wechatPay.getOrderId());
        String weChatOrderId = wechatPay.getWeChatOrderId();
        String payType = wechatPay.getPayType();
        String amount = wechatPay.getAmount();
        Date paymentDate = wechatPay.getPaymentDate();
        //改订单状态
        MallBooksOrderDO orderDO = orderService.lambdaQuery().eq(MallBooksOrderDO::getId, orderId).one();
        if (!WAIT_FREE.getType().equals(orderDO.getStatus())) {
            MallBooksOrderDO booksOrderDO = new MallBooksOrderDO();
            booksOrderDO.setId(orderId);
            booksOrderDO.setStatus(OrderStatusEnum.WAIT_FREE.getType().toString());
            booksOrderDO.setUpdateTime(new Date());
            booksOrderDO.setUpdateUser(SessionContext.getWechatUserId());
            orderMapper.updateDO(booksOrderDO);
        }
        //添加支付记录
        List<MallPaymentDO> list = paymentService.lambdaQuery().eq(MallPaymentDO::getOrderId, orderId).last("for update").list();
        if (CollectionUtils.isEmpty(list)) {
            MallPaymentRequest mallPaymentRequest = new MallPaymentRequest();
            mallPaymentRequest.setOrderId(orderId);
            mallPaymentRequest.setWxOrderNum(weChatOrderId);
            mallPaymentRequest.setPaymentDate(paymentDate);
            mallPaymentRequest.setPaymentMethod(payType);
            mallPaymentRequest.setAmount(new BigDecimal(amount));
            paymentService.add(mallPaymentRequest);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refundHandle(WechatRefund wechatPay) {
        Long orderId = wechatPay.getOrderId();
        Long specificationId = orderDetailsService.selectBookSpecificationId(orderId);
        String orderNum = wechatPay.getOrderNum();
        //归还库存
        Map<String, Long> map = new HashMap<>();
        map.put("specificationId", specificationId);
        map.put("quantity", wechatPay.getQuantity());
        specificationService.addQuantity(map);
        MallRefundPriceRequest priceRequest = new MallRefundPriceRequest();
        Long loginAccountId = wechatPay.getUserId();
        if (ADMIN_REFUND_PRICE.getType().equals(wechatPay.getOperationType())){
            Long refundId = refundsMapper.selectIdByOrderId(wechatPay.getOrderId());
            priceRequest.setRefundId(refundId);
            //修改订单状态
            orderMapper.updateStatus(orderId,BEFOR_SALE.getType().toString(),new Date());
            //修改订单详情，为已售后
            mallBooksOrderDetailsMapper.updateIsRefunds(orderId);
            //修改售后状态
            MallRefundsDO refundsDO = new MallRefundsDO();
            refundsDO.setOrderId(orderId);
            refundsDO.setStatus(OrderRefundEnum.WAN_CHENG.getType());
            refundsDO.setAdminId(loginAccountId);
            refundsDO.setUpdateTime(new Date());
            refundsDO.setUpdateUser(loginAccountId);
            refundsMapper.updateByOrderId(refundsDO);
        }else {
            //修改订单状态
            orderMapper.updateStatus(orderId,CANCEL.getType().toString(),new Date());
        }
        //添加退款记录
        priceRequest.setRefundNum(wechatPay.getRefundNum());
        priceRequest.setWxRefundNum(wechatPay.getWxRefundNum());
        priceRequest.setOrderNum(wechatPay.getOrderNum());
        priceRequest.setRefundPrice(new BigDecimal(wechatPay.getAmount()));
        priceRequest.setRefundType(wechatPay.getRefundType());
        priceRequest.setRefundTime(new Date());
        priceRequest.setCreateTime(new Date());
        priceRequest.setCreateUser(loginAccountId);
        Integer count =  refundPriceService.selectCountByOrderId(orderNum);
        if (count==0){
            refundPriceService.add(priceRequest);
        }
    }
}
